package netWork;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class Homework02ReceiverA {
    //接收方
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(9999);
        while (true){
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],0,4096);
            datagramSocket.receive(requestPacket);
            String request = new String(requestPacket.getData(),0, requestPacket.getLength());
            String response = null;
            if("四大名著".equals(request)){
                response = "三国演义 + 水浒传 + 红楼梦 + 西游记";
            }else if("0".equals(request)){
                response = request;
            }else {
                response = "what?";
            }
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(StandardCharsets.UTF_8),
                    response.getBytes(StandardCharsets.UTF_8).length,
                    requestPacket.getAddress(),requestPacket.getPort());
            datagramSocket.send(responsePacket);
            if(response.equals("0")){
                System.out.println("服务器结束...");
                break;
            }
            System.out.printf("[%s %d], req:%s resp:%s\n",requestPacket.getAddress().getHostAddress(),
                    requestPacket.getPort(),request,response);
        }
        datagramSocket.close();
    }

}
